package com.mfhcd.facepay.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProviders;

import com.mfhcd.facepay.R;
import com.mfhcd.facepay.utils.ClassUtil;
import com.mfhcd.facepay.viewmodel.BaseViewModel;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle3.components.support.RxFragment;

/**
 * Author：石强
 * E-Mail: shiqiang@mfhcd.com
 * Date：2019-08-30
 * 版权所有 © 现代金融控股（成都）有限公司
 */
public abstract class BaseFragment<VM extends BaseViewModel, SV extends ViewDataBinding> extends RxFragment {
    // ViewModel
    protected VM viewModel;
    // 布局view
    protected SV bindingView;
    protected Activity activity;
    protected Context mContext;
    protected RxPermissions mRxPermissions;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (Activity) context;
        mContext = context;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViewModel();
        initData();
        initListener();
        mRxPermissions = new RxPermissions(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_base, null);
        bindingView = DataBindingUtil.inflate(activity.getLayoutInflater(), initContentView(), null, false);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        bindingView.getRoot().setLayoutParams(params);
        LinearLayout mContainer = inflate.findViewById(R.id.container);
        mContainer.addView(bindingView.getRoot());
        return inflate;
    }

    /**
     * 初始化ViewModel
     */
    private void initViewModel() {
        Class<VM> viewModelClass = ClassUtil.getViewModel(this);
        if (viewModelClass != null) {
            // this.viewModel = ViewModelProviders.of(this).get(viewModelClass);
            this.viewModel = ViewModelProviders.of(getActivity()).get(viewModelClass);
            this.viewModel.setCurrentActivity(getActivity());
            this.viewModel.setBaseActivity((BaseActivity) activity);
        }
    }

    @Nullable
    @Override
    public Context getContext() {
        return activity;
    }

    protected abstract int initContentView();

    protected abstract void initData();

    protected abstract void initListener();
}
